package net.qhzw.geologr5.gis.service.system.service.impl;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import net.qhzw.geologr5.gis.api.system.entity.Role;
import net.qhzw.geologr5.gis.common.framework.utils.JsonResult;
import net.qhzw.geologr5.gis.common.security.utils.SecurityUtils;
import net.qhzw.geologr5.gis.service.system.entity.Dept;
import net.qhzw.geologr5.gis.service.system.entity.Member;
import net.qhzw.geologr5.gis.service.system.entity.UserRole;
import net.qhzw.geologr5.gis.service.system.mapper.*;
import net.qhzw.geologr5.gis.service.system.service.UserService;
import net.qhzw.geologr5.gis.service.system.vo.user.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


@Service
@Slf4j
public class UserServiceimple implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private DeptMapper deptMapper;


    /***
     * 编辑用户
     * @param entity
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult edit(UserVo entity) {
        log.info("编辑用户==UserServiceimple==method:edit==entity: {}", JSON.toJSONString(entity));
        try {
            Member user = new Member();
            BeanUtils.copyProperties(entity, user);
            int maxId = userMapper.selectMaxId();
            Integer userId = maxId + 1;
            if (user.getId() == null || user.getId() <= 0) {
                //新增
                user.setId(userId);
                user.setCreateTime(new Date());
                user.setPassword(SecurityUtils.encryptPassword(entity.getPassword()));
                memberMapper.insert(user);
                entity.setId(userId);
                return uploadUserRole(entity);
            } else {
                user.setUpdateTime(new Date());
                memberMapper.updateById(user);
                return uploadUserRole(entity);
            }
        } catch (Exception e) {
            log.error("编辑用户失败==UserServiceimple==method:edit==errMsg: {}", e.getMessage());
            //return JsonResult.error(e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }


    /***
     * 删除用户
     * @param userIds
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult deleteByIds(Integer[] userIds) {
        try {
            List<Integer> list = Arrays.asList(userIds);
            int row = userMapper.deleteBatchIds(list);
            if (row > 0) {
                return JsonResult.success();
            }
            return JsonResult.error("id不存在");
        } catch (Exception e) {
            log.error("删除用户失败==UserServiceimple==method:deleteByIds==errMsg: {}", e.getMessage());
            return JsonResult.error(e.getMessage());
        }

    }


    /***
     * 编辑用户关联属性
     * @return
     */
    private JsonResult uploadUserRole(UserVo member) {
        //查询角色信息
        List<Role> roles = new ArrayList<>();
        if (member.getRoleIds() != null && member.getRoleIds().length > 0) {
            List<Integer> list = Arrays.asList(member.getRoleIds());
            roles = roleMapper.selectBatchByIdList(list);
        }
        if (roles.isEmpty()) {
            return JsonResult.error("角色信息null");
        }
        //添加校色用户表
        for (Role role : roles) {
            UserRole userRole = new UserRole();
            userRole.setRoleId(role.getId());
            userRole.setUserId(member.getId());
            List<UserRole> userRoleList = userRoleMapper.selectByUserId(member.getId());
            if (userRoleList.isEmpty()) {
                //userRoleMapper.insert(userRole);
                userRoleMapper.insertUserRole(userRole);
            } else {
                //修改用户权限时 先把之前的权限删除 在添加
                List<Integer> idList = new ArrayList<>();
                userRoleList.forEach(data -> {
                    idList.add(data.getId());
                });
                userRoleMapper.deleteBatchIds(idList);
                //userRoleMapper.insert(userRole);
                userRoleMapper.insertUserRole(userRole);
            }
        }
        //添加部门
        Dept dept = deptMapper.selectDeptById(member.getDeptId());
        if (dept == null) {
            return JsonResult.error("数据权限信息null");
        }
        dept.setDictId(member.getDictId());
        deptMapper.updateById(dept);
        return JsonResult.success();
    }


}
